package com.edu.solr_news.service.impl;

import com.edu.solr_news.bean.DataModel;
import com.edu.solr_news.bean.News;
import com.edu.solr_news.dao.NewsDao;
import com.edu.solr_news.service.NewsSearceSevice;
import com.edu.solr_news.util.CiYun;
import com.edu.solr_news.util.CountWordUtil;
import com.edu.solr_news.util.DateTimeUtil;
import com.edu.solr_news.util.Pageutil;
import com.google.gson.Gson;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class NewsSearchServiceImpl implements NewsSearceSevice {

    @Autowired
    private SolrClient solrClient;
    @Autowired
    private CountWordUtil countWordUtil;
    @Autowired
    private DateTimeUtil dateTimeUtil;
    @Autowired
    private NewsDao newsDao;
    @Autowired
    private CiYun ciYun;
    @Autowired
    private Gson gson;



    //信息检索
    @Override
    public Pageutil search(String keyword, String page, String limit,String sort) throws IOException, SolrServerException {
        /*
        查询条件
         */
        SolrQuery query=new SolrQuery();
        if(StringUtils.isEmpty(keyword)||keyword==null){
            query.set("q", "*:*");
            keyword="";
        }else {
            //直接使用q查询暂不设默认域
            query.set("q", "news_title:"+keyword+" OR "+"news_content:"+keyword);
        }

        int limitnums= 10;
        if(StringUtils.isEmpty(limit) || limit==null){
            query.setRows(limitnums);
        }else {
            query.setRows(Integer.valueOf(limit));
            limitnums=Integer.valueOf(limit);
        }

        //设置分页功能
        if(StringUtils.isEmpty(page)||page==null){
            query.setStart(0);
            page="1";
        }
        else {
            query.setStart((Integer.valueOf(page)-1)*limitnums);
        }


        //设置排序规则
        if(StringUtils.isEmpty(sort) || sort.equals("1") || sort==null){
            query.addSort("news_time", SolrQuery.ORDER.desc);
        }else {
            query.addSort("news_time", SolrQuery.ORDER.asc);
        }
        //设置高亮
        query.setHighlight(true);
        query.addHighlightField("news_title");
        query.addHighlightField("news_content");
        query.setHighlightSimplePre("<font color='red'>");
        query.setHighlightSimplePost("</font>");
        QueryResponse response = solrClient.query(query);
        //得到查询总数
        int count= (int) response.getResults().getNumFound();
        //得到高亮数据
        Map<String, Map<String, List<String>>> map
                = response.getHighlighting();
        List<News> list = response.getBeans(News.class);
        for (News news : list) {
            //词频统计
            String word = countWordUtil.searchWord(news.getContent());
            news.setKeyword(word);
            //高亮内容设置
            Map<String, List<String>> map1
                    = map.get(news.getId());
            List<String> list1 = map1.get("news_title");
            if(list1!=null){
                news.setTitle(list1.get(0));
            }
            List<String> list2 = map1.get("news_content");
            if(list2!=null){
                news.setContent(list2.get(0));
            }
            //日期格式化处理
            news.setTime(dateTimeUtil.formatCSTDate(news.getTime()));
        }
        //查询结果封装
        Pageutil pageutil=new Pageutil();
        pageutil.setCount(count);
        pageutil.setLimit(limitnums);
        pageutil.setPage(Integer.valueOf(page));
        pageutil.setKeyword(keyword);
        pageutil.setNews(list);
        return pageutil;
    }

    //导出数据
    @Override
    public Pageutil searchForImport(String keyword, String page, String limit, String sort) throws IOException, SolrServerException {
         /*
        查询条件
         */
        SolrQuery query=new SolrQuery();
        if(StringUtils.isEmpty(keyword)||keyword==null){
            query.set("q", "*:*");
            keyword="";
        }else {
            //直接使用q查询暂不设默认域
            query.set("q", "news_title:"+keyword+" OR "+"news_content:"+keyword);
        }

        int limitnums= 10;
        if(StringUtils.isEmpty(limit) || limit==null){
            query.setRows(limitnums);
        }else {
            query.setRows(Integer.valueOf(limit));
            limitnums=Integer.valueOf(limit);
        }

        //设置分页功能
        if(StringUtils.isEmpty(page)||page==null){
            query.setStart(0);
            page="1";
        }
        else {
            query.setStart((Integer.valueOf(page)-1)*limitnums);
        }


        //设置排序规则
        if(StringUtils.isEmpty(sort) || sort.equals("1") || sort==null){
            query.addSort("news_time", SolrQuery.ORDER.desc);
        }else {
            query.addSort("news_time", SolrQuery.ORDER.asc);
        }

        QueryResponse response = solrClient.query(query);
        //得到查询总数
        int count= (int) response.getResults().getNumFound();
        List<News> list = response.getBeans(News.class);
        for (News news : list) {
            //词频统计
            String word = countWordUtil.searchWord(news.getContent());
            news.setKeyword(word);
            //日期格式化处理
            news.setTime(dateTimeUtil.formatCSTDate(news.getTime()));
        }
        //查询结果封装
        Pageutil pageutil=new Pageutil();
        pageutil.setCount(count);
        pageutil.setLimit(limitnums);
        pageutil.setPage(Integer.valueOf(page));
        pageutil.setKeyword(keyword);
        pageutil.setNews(list);
        return pageutil;
    }


    //新闻详细页面
    @Override
    public News searchById(String id) throws IOException, SolrServerException {
        News newsById=new News();
        if(StringUtils.isEmpty(id) || id==null){
            return null;
        }else {
            newsById = newsDao.findNewsById(id);
        }

        if(newsById!=null){
            newsById.setTime(dateTimeUtil.formatCSTDate(newsById.getTime()));
            //更新点击量
            int onclink=newsDao.findOnclick(id);
            newsDao.updateOnclick(id,onclink+1);
            return newsById;
        }

        return null;
    }

    //最新新闻
    @Override
    public Pageutil newNews(String page, String limit) throws IOException, SolrServerException {
           /*
        查询条件
         */
        SolrQuery query=new SolrQuery();
        query.set("q", "*:*");
        int limitnums= 10;
        if(StringUtils.isEmpty(limit) || limit==null){
            query.setRows(limitnums);
        }else {
            query.setRows(Integer.valueOf(limit));
            limitnums=Integer.valueOf(limit);
        }

        //设置分页功能
        if(StringUtils.isEmpty(page)||page==null){
            query.setStart(0);
            page="1";
        }
        else {
            query.setStart((Integer.valueOf(page)-1)*limitnums);
        }

        //设置排序规则 按日期进行排序
        query.addSort("news_time", SolrQuery.ORDER.desc);

        QueryResponse response = solrClient.query(query);
        //得到查询总数
        int count= (int) response.getResults().getNumFound();
        List<News> list = response.getBeans(News.class);
        for (News news : list) {
            //词频统计
            String word = countWordUtil.searchWord(news.getContent());
            news.setKeyword(word);
            //日期格式化处理
            news.setTime(dateTimeUtil.formatCSTDate(news.getTime()));
        }

        //查询结果封装
        Pageutil pageutil=new Pageutil();
        pageutil.setCount(count);
        pageutil.setLimit(limitnums);
        pageutil.setPage(Integer.valueOf(page));
        pageutil.setNews(list);
        return pageutil;
    }

    //热点新闻
    @Override
    public Pageutil hotNews(String page, String limit) {
        int limitnums= 10;
        if(StringUtils.isEmpty(limit) || limit==null){
            limitnums=10;
        }else {
            limitnums=Integer.valueOf(limit);
        }

        int pagenum=0;
        if(StringUtils.isEmpty(page)||page==null){
            pagenum=0;
        }
        else {
            pagenum=(Integer.valueOf(page)-1)*limitnums;
        }

        //查询
        List<News>  list = newsDao.findByOnclick(pagenum,limitnums);

        for (News news : list) {
            //词频统计
            String word = countWordUtil.searchWord(news.getContent());
            news.setKeyword(word);
            //日期格式化处理
            news.setTime(dateTimeUtil.formatCSTDate(news.getTime()));
        }

        //查询结果封装
        Pageutil pageutil=new Pageutil();
        pageutil.setCount(newsDao.findNewsCount());
        pageutil.setLimit(limitnums);
        pageutil.setPage(pagenum+1);
        pageutil.setNews(list);
        return pageutil;
    }

    //首页词云动态生成
    @Override
    public String indexCiyun(HttpServletRequest request,String starttime,String endtime,String wordnum)
            throws IOException, SolrServerException {
        SimpleDateFormat nameDf = new SimpleDateFormat("yyyyMMddHHmmss");
        //获取词云图片编号
        Date date = new Date();
        String ciyunName = nameDf.format(date);
        String serverpath = "/usr/local/solr_news-v1.0/solr_news-server/img/";
       // String serverpath = "E:/img/";
        File ciyunImg = new File(serverpath+ciyunName+".png");
        if(ciyunImg.exists()){
            return "/OTA/"+ciyunName+".png";
        }
        else {
            //生成当天日期词云
            List<String> texts=newsDao.findContent(starttime,endtime);
            String text="";
            for (String s: texts) {
                text=text+s;
            }
            ciYun.createCiYun(text,ciyunImg.getPath(),wordnum);
            return "/OTA/"+ciyunName+".png";
        }

    }

    //图表数据生成
    @Override
    public String indexEchart(String starttime,String endtime){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前日期
        Date date = new Date();
        String nowdate = df.format(date);
        if(starttime==null|| StringUtils.isEmpty(starttime)){
            starttime=nowdate;
        }
        if(endtime==null|| StringUtils.isEmpty(endtime)){
            endtime=nowdate;
        }
        List<DataModel> dataModels;
        //查询结果
        dataModels=newsDao.countNum(starttime,endtime);
        return gson.toJson(dataModels);
    }

}
